<template>
  <div class="finance-page">
    <van-nav-bar title="账单管理" safe-area-inset-top>
      <template #right>
        <van-button 
          plain 
          type="warning" 
          size="small" 
          class="nav-button"
          @click="showGeneralRefundForm"
        >
          申请退款
        </van-button>
        <van-button 
          plain 
          type="primary" 
          size="small"
          class="nav-button" 
          @click="showRefundHistory"
        >
          退款记录
        </van-button>
      </template>
    </van-nav-bar>
    <!-- 3. 当前账单显示 -->
    <div class="bill-display-container">
      <van-loading v-if="loading" class="loading-center" />
      <van-empty v-else-if="!currentBill" description="未能加载账单信息，请稍后重试" />
      
      <div v-else class="bill-card">
        <!-- 已支付印章 -->
        <div v-if="currentBill.status === 'paid'" class="paid-stamp"></div>
        
        <div class="card-header">
          <div class="bill-info">
            <h3 class="bill-title">{{ currentBill.elderlyName }} - {{ currentBill.billMonth }}</h3>
            <p class="bill-subtitle">账单ID: {{ currentBill.id }}</p>
          </div>
          <van-tag :type="getStatusType(currentBill.status)">{{ currentBill.statusDesc }}</van-tag>
        </div>

        <div class="card-body">
          <div class="amount-display">
            <span class="amount-label">应付金额</span>
            <span class="amount-value">¥ {{ currentBill.totalAmount.toFixed(2) }}</span>
          </div>
          <div class="date-info">
            <p>生成日期: {{ formatDate(currentBill.createdAt) }}</p>
            <p>截止日期: {{ formatDate(currentBill.dueDate) }}</p>
            <p v-if="currentBill.paidAt">支付时间: {{ currentBill.paidAt }}</p>
          </div>
        </div>

        <!-- 费用明细 -->
        <div class="bill-details">
          <h4 class="details-title">费用明细</h4>
          <div class="details-list">
            <div v-for="detail in currentBill.details" :key="detail.id" class="detail-item">
              <div class="detail-info">
                <span class="detail-type">{{ detail.itemTypeDesc }}</span>
                <span class="detail-desc">{{ detail.itemDescription }}</span>
              </div>
              <span class="detail-amount">¥ {{ detail.amount.toFixed(2) }}</span>
            </div>
          </div>
        </div>

        <!-- [MODIFIED]: Footer now only contains the pay button -->
        <div class="card-footer">
          <van-button
            v-if="currentBill.status !== 'paid'"
            type="primary"
            size="small"
            round
            @click="goToPayment(currentBill.id)"
          >
            立即支付
          </van-button>
        </div>
      </div>
    </div>

    <!-- [MODIFIED]: 退款申请表单弹窗 (now a general form) -->
    <van-popup
      v-model:show="showRefundPopup"
      position="bottom"
      :style="{ height: '80%' }"
      closeable
    >
      <div class="refund-popup-content">
        <van-nav-bar title="申请退款" />
        <div class="refund-form">
          <van-cell-group inset>
            <van-field
              v-model="refundForm.billId"
              label="关联账单ID"
              type="number"
              placeholder="请输入需要退款的账单ID"
              required
              :rules="[{ required: true, message: '请输入账单ID' }]"
            />
            <van-field
              v-model="refundForm.amount"
              label="退款金额"
              type="number"
              placeholder="请输入退款金额"
              required
              :rules="[{ required: true, message: '请输入退款金额' }]"
            />
            <van-field
              v-model="refundForm.reason"
              label="退款原因"
              type="textarea"
              placeholder="请详细说明退款原因"
              rows="3"
              required
              :rules="[{ required: true, message: '请输入退款原因' }]"
            />
          </van-cell-group>
        </div>
        <div class="popup-footer">
          <van-button block round type="primary" @click="submitRefund" :loading="submitting">
            提交申请
          </van-button>
        </div>
      </div>
    </van-popup>

    <!-- 退款记录页面 -->
    <van-popup
      v-model:show="showRefundHistoryPopup"
      position="bottom"
      :style="{ height: '100%' }"
      closeable
    >
      <div class="refund-history-content">
        <van-nav-bar title="退款记录" />
        <div class="refund-list">
          <van-loading v-if="refundLoading" class="loading-center" />
          <van-empty v-else-if="refundList.length === 0" description="暂无退款记录" />
          
          <div v-else v-for="refund in refundList" :key="refund.id" class="refund-card">
            <div class="refund-header">
              <span class="refund-title">退款申请 (账单: {{ refund.billId }})</span>
              <van-tag :type="getRefundStatusType(refund.status)">{{ getRefundStatusText(refund.status) }}</van-tag>
            </div>
            <div class="refund-body">
              <div class="refund-info">
                <p><span class="label">申请金额:</span> ¥{{ refund.amount.toFixed(2) }}</p>
                <p><span class="label">申请时间:</span> {{ formatDate(refund.createdAt) }}</p>
                <p><span class="label">退款原因:</span> {{ refund.reason }}</p>
                <p v-if="refund.remarks"><span class="label">备注:</span> {{ refund.remarks }}</p>
              </div>
            </div>
            <div class="refund-footer">
              <van-button 
                v-if="refund.status === 'PENDING'"
                plain 
                type="danger" 
                size="small"
                @click="deleteRefund(refund.id)"
              >
                撤销申请
              </van-button>
            </div>
          </div>
        </div>
      </div>
    </van-popup>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { showToast, showConfirmDialog } from 'vant';
import { getBill } from '@/api/bills';
import { 
  createRefundRequest, 
  getRefundRecordsByUserId, 
  deleteRefundRecord 
} from '@/api/refund';

// 基础状态
const loading = ref(false);
const billId = ref('1'); // 写死查询ID为1
const currentBill = ref(null);
const billHistory = ref([]); // 存储查询历史，用于计算总支出

// 弹窗状态
const showRefundPopup = ref(false);
const showRefundHistoryPopup = ref(false);

// 退款相关状态
const submitting = ref(false);
const refundLoading = ref(false);
const refundList = ref([]);

// [MODIFIED]: Generic refund form state
const refundForm = ref({
  billId: '',
  amount: '',
  reason: ''
});

// 计算属性
const totalExpenditure = computed(() => {
  return billHistory.value
    .filter(bill => bill.status === 'paid')
    .reduce((sum, bill) => sum + bill.totalAmount, 0);
});

const pendingAmount = computed(() => {
  if (!currentBill.value) return 0;
  return currentBill.value.status !== 'paid' ? currentBill.value.totalAmount : 0;
});

// [MODIFIED]: Automatically load bill data when the component is mounted
onMounted(() => {
  loadBillById();
});

// 根据账单ID加载账单
const loadBillById = async () => {
  if (!billId.value) {
    showToast('账单ID不能为空');
    return;
  }
  try {
    loading.value = true;
    const response = await getBill(billId.value);
    
    // Check various possible response structures
    let billData = null;
    if (response && response.id) {
      billData = response;
    } else if (response && response.code === 200 && response.data) {
      billData = response.data;
    }

    if (billData) {
      currentBill.value = billData;
      // Update history for total expenditure calculation
      const existingIndex = billHistory.value.findIndex(bill => bill.id === billData.id);
      if (existingIndex >= 0) {
        billHistory.value[existingIndex] = billData;
      } else {
        billHistory.value.push(billData);
      }
    } else {
      showToast(response.msg || '加载失败');
      currentBill.value = null;
    }
  } catch (error) {
    console.error('加载账单失败:', error);
    showToast('加载失败，请重试');
    currentBill.value = null;
  } finally {
    loading.value = false;
  }
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = { 'unpaid': 'primary', 'paid': 'success', 'overdue': 'danger' };
  return statusMap[status] || 'default';
};

// [NEW]: Show the general refund form
const showGeneralRefundForm = () => {
  // Reset the form to be blank
  refundForm.value = { billId: '', amount: '', reason: '' };
  showRefundPopup.value = true;
};

// 提交退款申请
const submitRefund = async () => {
  if (!refundForm.value.billId || !refundForm.value.amount || !refundForm.value.reason) {
    showToast('请填写完整信息');
    return;
  }
  if (parseFloat(refundForm.value.amount) <= 0) {
    showToast('退款金额必须大于0');
    return;
  }

  try {
    submitting.value = true;
    const data = {
      billId: parseInt(refundForm.value.billId, 10),
      // Assuming the backend knows the user from the session/token.
      // If elderlyUserId is needed, you might get it from a central store.
      // For this mock, we'll use a hardcoded user id.
      elderlyUserId: getCurrentUserId(), 
      amount: parseFloat(refundForm.value.amount),
      reason: refundForm.value.reason
    };

    await createRefundRequest(data);
    showToast('退款申请提交成功');
    showRefundPopup.value = false;

  } catch (error) {
    console.error('提交退款申请失败:', error);
    showToast('提交失败，请重试');
  } finally {
    submitting.value = false;
  }
};

// 显示退款记录
const showRefundHistory = async () => {
  try {
    refundLoading.value = true;
    showRefundHistoryPopup.value = true;
    const userId = getCurrentUserId();
    const response = await getRefundRecordsByUserId(101);
    console.log(response);
    
    refundList.value = response || [];
  } catch (error) {
    console.error('获取退款记录失败:', error);
    showToast('获取退款记录失败，请重试');
    refundList.value = [];
  } finally {
    refundLoading.value = false;
  }
};

// 删除退款申请
const deleteRefund = async (refundId) => {
  try {
    await showConfirmDialog({ title: '确认撤销', message: '确定要撤销这个退款申请吗？' });
    const response = await deleteRefundRecord(refundId);
    if (response.code === 200) {
      showToast('撤销成功');
      await showRefundHistory(); // Refresh the list
    } else {
      showToast(response.msg || '撤销失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤销退款申请失败:', error);
      showToast('撤销失败，请重试');
    }
  }
};

// 获取退款状态相关样式和文本
const getRefundStatusType = (status) => {
  const statusMap = { 'pending': 'warning', 'approved': 'success', 'rejected': 'danger', 'completed': 'success' };
  return statusMap[status] || 'default';
};
const getRefundStatusText = (status) => {
  const statusMap = { 'pending': '待审核', 'approved': '已通过', 'rejected': '已拒绝', 'completed': '已完成' };
  return statusMap[status] || '未知状态';
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString.includes(' ') ? dateString.replace(' ', 'T') : dateString);
  if (isNaN(date.getTime())) return dateString;
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
};

// 模拟获取当前用户ID
const getCurrentUserId = () => 1001;

// 跳转到支付页面
const goToPayment = (billId) => {
  showToast(`正在跳转到支付页面，账单ID: ${billId}`);
  // router.push(`/finance/payment/${billId}`);
};
</script>

<style scoped>
.finance-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

/* [NEW]: Style for nav bar buttons */
.nav-button {
  margin-left: 8px;
  padding-bottom: 10px;
}

.loading-center {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.overview-card-wrapper {
  padding: 16px 16px 0 16px;
  background-color: #f7f8fa;
}
.overview-card {
  display: flex;
  justify-content: space-around;
  padding: 20px;
  background: linear-gradient(135deg, #4b8eff, #3a7afe);
  border-radius: 12px;
  color: white;
  box-shadow: 0 8px 16px rgba(58, 122, 254, 0.2);
}
.overview-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}
.overview-item .label {
  font-size: 13px;
  opacity: 0.8;
}
.overview-item .value {
  font-size: 22px;
  font-weight: bold;
}
.overview-item .text-warning {
  color: #ffeb3b;
}
.divider {
  width: 1px;
  background-color: rgba(255, 255, 255, 0.3);
}

.bill-input-container {
  padding: 16px;
}

.bill-display-container {
  padding: 0 16px;
}
.bill-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 6px;
  margin-top: 10px;
  box-shadow: 0 8px 16px rgba(100, 101, 102, 0.08);
  position: relative;
  overflow: hidden;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 12px;
  border-bottom: 1px solid #f2f3f5;
}
.bill-info .bill-title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  margin: 0 0 4px 0;
}
.bill-info .bill-subtitle {
  font-size: 12px;
  color: #969799;
  margin: 0;
}
.card-body {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px 0;
}
.amount-display .amount-label {
  font-size: 13px;
  color: #969799;
}
.amount-display .amount-value {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #323233;
  margin-top: 4px;
}
.date-info {
  text-align: right;
  font-size: 12px;
  color: #969799;
}
.date-info p {
  margin: 4px 0;
}

.bill-details {
  margin: 16px 0;
  padding: 16px 0;
  border-top: 1px solid #f2f3f5;
}
.details-title {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
  margin: 0 0 12px 0;
}
.details-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f7f8fa;
  border-radius: 6px;
}
.detail-info .detail-type {
  font-size: 12px;
  color: #969799;
}
.detail-info .detail-desc {
  font-size: 14px;
  color: #323233;
}
.detail-amount {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
}
.card-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  padding-top: 12px;
  border-top: 1px solid #f2f3f5;
  min-height: 32px;
}

.paid-stamp {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 80px;
  height: 80px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="45" stroke="%2307c160" stroke-width="3" fill="none"/><text x="50" y="58" font-size="24" font-family="sans-serif" fill="%2307c160" text-anchor="middle" font-weight="bold">已结清</text></svg>');
  background-size: contain;
  opacity: 0.15;
  transform: rotate(15deg);
  pointer-events: none;
}

.refund-popup-content,
.refund-history-content {
  background-color: #f7f8fa;
  height: 100%;
}
.refund-form {
  padding: 16px 0;
}

.refund-list {
  padding: 16px;
}
.refund-card {
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 16px;
  padding: 16px;
  box-shadow: 0 8px 16px rgba(100, 101, 102, 0.08);
}
.refund-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #f2f3f5;
}
.refund-title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}
.refund-body {
  padding: 16px 0;
}
.refund-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #646566;
}
.refund-info .label {
  color: #969799;
}
.refund-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 12px;
  border-top: 1px solid #f2f3f5;
}

.popup-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  padding-bottom: calc(16px + env(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}
</style>